from flask import Flask, request, jsonify
from sina_login_py import sn_login
import muggle_ocr
import requests
import re

app = Flask(__name__)
sdk = muggle_ocr.SDK(conf_path='./weibo_code/wb-CNNX-GRU-H64-CTC-C1_model.yaml')


@app.route('/cookies', methods=['POST'])
def get_cookie():
    login_data = request.form
    username = login_data.get('username', '')
    password = login_data.get('password', '')
    if password and username:
        cookies = sn_login(username, password, sdk=sdk).cookies()
        if cookies:
            return jsonify(cookies)
        else:
            return 'Login Failed', 404
    return 'Check You Login_info', 403


# 代理模式
@app.route('/cookies_proxy', methods=['POST'])
def cookie_proxy():
    login_data = request.form
    username = login_data.get('username', '')
    password = login_data.get('password', '')
    proxy = login_data.get('proxy', '')  # 39.69.72.148:4260
    if password and username and proxy:
        cookies = sn_login(username, password, proxy, sdk=sdk).cookies()
        if isinstance(cookies, dict):
            return jsonify(cookies)
        if isinstance(cookies, str):
            return 'Proxy unavailable', 404
        else:
            return 'Login Failed', 404
    return 'Check You Login_info', 403


# 测试接口是否可用
@app.route('/test')
def test():
    cookies = sn_login('13695540308', 'zjy19970927', sdk=sdk).cookies()
    if cookies:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
            'cookie': cookies.get('cookies', '')
        }
        resp = requests.get(url='https://weibo.com/u/5233528486/home?wvr=5', headers=headers)
        if resp.status_code != 200:
            return 'Api Unavailable', 403
        else:
            nick = re.findall("\$CONFIG\['uid']='(.*?)'", resp.text, re.S)[0]
            if nick == '5233528486':
                return 'Api Is Available'
            else:
                return 'Api Unavailable', 403
    else:
        return 'Login Failed', 403


if __name__ == '__main__':
    app.run(host='0.0.0.0')
